<template>
  <div>
    <img src="../imgs/24_zhongqiu_mbanner_pc.png" height="80" width="100%"/>
    <el-header class="header">
      <div class="logo">
        <img src="../imgs/home_logoV1-2.png" height="60" width="474"/></div>
      <el-menu :default-active="activeIndex" class="top-nav-menu" mode="horizontal" @select="handleSelect">
        <el-menu-item index="8" style="font-size: 30px;font-weight: 700" @click="xianhua">鲜花大厅</el-menu-item>
        <el-menu-item index="1">首页</el-menu-item>
        <el-menu-item index="7"
                      @mouseenter="showWechatImage = true"
                      @mouseleave="showWechatImage = false"
                      class="wechat-menu-item">
          关注微信
          <!-- 条件渲染微信图片 -->
          <div v-if="showWechatImage" class="wechat-image-box">
            <img src="../imgs/vx.jpg" alt="关注我们的微信" />
          </div>
        </el-menu-item>
        <el-menu-item index="2"
                      @mouseenter="showWechatImage2 = true"
                      @mouseleave="showWechatImage2 = false"
                      class="wechat-menu-item">
          花礼网app
          <!-- 条件渲染花礼网app图片 -->
          <div v-if="showWechatImage2" class="wechat-image-box">
            <img src="../imgs/vx2.jpg" alt="关注我们的花礼网app" />
          </div>
        </el-menu-item>
<!--        <el-menu-item index="2" @click="handleAppClick">花礼网app</el-menu-item>-->
        <el-menu-item index="4" @click="goToOrders">订单查询</el-menu-item>
        <el-menu-item index="5" class="el-icon-headset" @click="pinglun">评论中心</el-menu-item>
        <el-menu-item index="6" class="cart-menu-item" @click="goToCart">
          <el-badge :value="cartCount" class="item" :max="99">
            <el-tooltip class="item" effect="dark" content="购物车" placement="bottom">
              <i class="el-icon-shopping-cart-2"></i>
            </el-tooltip>
          </el-badge>
        </el-menu-item>
        <el-menu-item index="3" class="login-menu-item">
          <el-dropdown v-if="username" @command="handleCommand">
            <span class="el-dropdown-link">
              你好, <span style="color: red">{{ username }}</span>
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="personal">个人中心</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <template v-else>
            你好，请登录注册
          </template>
        </el-menu-item>
        <el-menu-item>
          <el-avatar :size="60" :src="src" shape="square">
            <img src="../imgs/error.png" alt="头像"/>
          </el-avatar>
        </el-menu-item>
      </el-menu>
    </el-header>

    <!-- 条件渲染广告 -->
    <AdComponent v-if="showAd"/>

    <!-- 条件渲染视频 -->
    <div v-if="showVideo" class="video-container">
      <!-- 请将下面的链接替换为实际的 Bilibili 视频嵌入链接 -->
      <iframe width="560" height="315" :src="videoUrl" frameborder="0"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowfullscreen></iframe>
    </div>

    <!-- 条件渲染轮播图 -->
    <LunBoTu v-if="showCarousel"/>

    <!-- 条件渲染个人中心页面 -->
    <div v-if="showPersonalCenter" class="personal-center">
      <!--  表格：装主体数据   -->
      <el-table
          ref="multipleTable"
          :data="users"
          tooltip-effect="dark"
          style="width: 70%; height: 400px; position: relative; left: 25%; top: 15px"
      >
        <el-table-column prop="id" label="用户编号" width="120"></el-table-column>
        <el-table-column prop="username" label="用户名称" width="120"></el-table-column>
        <el-table-column prop="password" label="用户密码" width="120"></el-table-column>
        <el-table-column prop="iphone" label="用户电话" width="120"></el-table-column>
        <el-table-column label="用户头像" width="120">
          <template slot-scope="scope">
            <el-avatar :size="60" :src="scope.row.src" @error="errorHandler" shape="square">
              <img src="../imgs/error.png" alt="默认头像"/>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="openUpdateUser(scope.row)"
                style="position: relative;top: 20px"></el-button>
            <el-tooltip class="item" effect="dark" content="谨慎使用" placement="top"
                        style="position: relative; left: 40px; top: -20px">
              <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 模态框 -->
    <div>
      <el-dialog
          title="修改用户信息"
          :visible.sync="dialogVisible"
          width="30%"
          @close="resetForm"
      >
        <el-form :model="userForm">
          <el-form-item label="用户名称" :label-width="formLabelWidth">
            <el-input v-model="userForm.username" autocomplete="off" readonly></el-input>
          </el-form-item>
          <el-form-item label="用户密码" :label-width="formLabelWidth">
            <el-input type="text" v-model="userForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户电话" :label-width="formLabelWidth">
            <el-input v-model="userForm.iphone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户头像" :label-width="formLabelWidth">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:9091/file/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img v-if="userForm.src" :src="userForm.src" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
      <el-button @click="guanbi">取 消</el-button>
      <el-button type="primary" @click="updateUser">确 定</el-button>
    </span>
      </el-dialog>
    </div>


    <footer class="footer">
      <img src="../imgs/21_logoupdate_banner_top.png" height="120" width="1690"/>
      <div class="container">
        <div class="footer-links">
          <h3>关于我们</h3>
          <ul>
            <li><a href="#">公司简介</a></li>
            <li><a href="#">媒体报道</a></li>
            <li><a href="#">企业团购</a></li>
            <li><a href="#">友情链接</a></li>
          </ul>
        </div>
        <div class="footer-contact">
          <h3>联系方式</h3>
          <p>电话: 123-456-7890</p>
          <p>Email: contact@hua.com</p>
        </div>
        <div class="footer-legal">
          <p>&copy; 2005-2024 花礼网版权所有</p>
          <p>ICP经营许可证: 粤B2-20050744 粤ICP备09171662号</p>
        </div>
        <div class="footer-social">
          <a href="#" class="social-icon"><i class="fab fa-weibo"></i></a>
          <a href="#" class="social-icon"><i class="fab fa-wechat"></i></a>
          <a href="#" class="social-icon"><i class="fab fa-linkedin-in"></i></a>
        </div>
      </div>
    </footer>
  </div>
</template>

<script>
import AdComponent from './AdComponent.vue';

import {
  Header as ElHeader,
  Menu,
  MenuItem,
  Badge,
  Tooltip,
  Dropdown,
  DropdownMenu,
  DropdownItem,
  Input,
  Button,
  Select,
  Option,
  InputNumber,
  Aside,
  Main,
  Carousel,
  CarouselItem
} from 'element-ui';

import LunBoTu from "@/components/LunBoTu.vue";
import request from "@/utils/request";
import {removeToken} from "@/utils/auth";

export default {
  name: 'UserMain',
  components: {
    LunBoTu,
    AdComponent,
    [ElHeader.name]: ElHeader,
    [Menu.name]: Menu,
    [MenuItem.name]: MenuItem,
    [Badge.name]: Badge,
    [Tooltip.name]: Tooltip,
    [Dropdown.name]: Dropdown,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Input.name]: Input,
    [Button.name]: Button,
    [Select.name]: Select,
    [Option.name]: Option,
    [InputNumber.name]: InputNumber,
    [Aside.name]: Aside,
    [Main.name]: Main,
    [Carousel.name]: Carousel,
    [CarouselItem.name]: CarouselItem,
  },
  data() {
    return {
      videoUrl: 'https://www.bilibili.com/video/BV1rT411g71g?t=6.0', // 替换为您的视频 URL
      showVideo: false, // 控制视频的显示
      showWechatImage: false, // 控制“关注微信”图片的显示
      showWechatImage2: false, // 控制“花礼网app”图片的显示
      showAd: true, // 控制广告
      userForm: {
        id: 0,
        username: '',
        password: '',
        iphone: '',
        src: '',
      },
      activeIndex: '1', // 默认激活的菜单项
      cartCount: 0, // 购物车数量
      username: '', // 存储用户名
      src: '', // 存储头像地址
      user: { // 存储用户信息
        id: 0,
        username: '',
        src: ''
      },
      showCarousel: true, // 控制轮播图的显示
      showPersonalCenter: false, // 控制个人中心的显示
      title: '个人中心', // 模态框标题
      users: [], // 存储用户数据的数组
      dialogVisible: false, // 控制模态框显示
      formLabelWidth: '120px', // 表单项的标签宽度
      originalPassword: '', // 保存用于比较的原始密码
      uid: 0, // 用户id
    };
  },

  methods: {
    handleAppClick() {
      this.showVideo = true;
    },

    pinglun() {
      this.$router.push('/pinglun');
    },

    // 跳转到订单查询页面
    goToOrders() {
      if (this.username != '' && this.username != null) {
        // 如果用户名不为空，跳转到 goShops.vue 页面
        this.$router.push('/userOrder');
      } else {
        // 如果用户名为空，提示用户先登录
        this.$message({
          type: 'warning',
          message: '请先登录'
        });
      }
    },
    // 处理点击购物车的行为
    goToCart() {
      if (this.username != '' && this.username != null) {
        // 如果用户名不为空，跳转到 goShops.vue 页面
        this.$router.push('/goShop');
      } else {
        // 如果用户名为空，提示用户先登录
        this.$message({
          type: 'warning',
          message: '请先登录'
        });
      }
    },

    // 跳转鲜花页面
    xianhua() {
      this.$router.push('/xianHua');
    },
    //--------------删除--------------------------
    deleteUser() {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '删除中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const userId = this.userForm.id; // 获取用户ID
        this.$axios({
          url: `http://localhost:9091/user/delete/${userId}`, // 将id直接拼接到URL中
          method: "post"
        }).then((res) => {
          loading.close();
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            this.dialogVisible = false;
            this.$router.push('/userLogin');
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch((error) => {
          loading.close();
          console.error("删除用户失败:", error);
          this.$message.error('删除用户时发生错误');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // ---------------------------修改------------------------
    openUpdateUser(row) {
      this.title = "修改用户信息";
      this.dialogVisible = true; // 打开模态框
      this.userForm.id = row.id;
      this.userForm.username = row.username;
      this.userForm.password = row.password; // 初始化密码
      this.userForm.iphone = row.iphone;
      this.userForm.src = row.src;
      this.originalPassword = row.password; // 保存原始密码
    },

    // 更新用户信息
    // updateUser() {
    //   // 检查用户是否填写了必要的信息
    //   if (!this.userForm.username || !this.userForm.iphone || (this.userForm.password !== this.originalPassword && !this.userForm.password)) {
    //     this.$message.error('请填写完整的用户信息');
    //     return;
    //   }
    //   // 发送更新请求
    //   this.$axios({
    //     url: "http://localhost:9091/user/update",
    //     method: "post",
    //     data: this.userForm
    //   }).then((res) => {
    //     if (res.data.code == 200) {
    //       this.$message({
    //         type: 'success',
    //         message: res.data.msg
    //       });
    //       this.dialogVisible = false; // 关闭模态框
    //       // 如果密码被修改，则跳转到登录页面
    //       if (this.userForm.password !== this.originalPassword) {
    //         this.$router.push('/userLogin');
    //         this.resetForm();
    //       } else {
    //         // 否则，重新加载用户数据
    //         this.getToken();
    //         this.resetForm();
    //         //   刷新
    //         // window.location.reload(true);
    //       }
    //     } else {
    //       this.$message.error(res.data.msg);
    //     }
    //   });
    // },
    updateUser() {
      // 检查用户是否填写了必要的信息
      if (!this.userForm.username || !this.userForm.iphone || (this.userForm.password !== this.originalPassword && !this.userForm.password)) {
        this.$message.error('请填写完整的用户信息');
        return;
      }
      // 发送更新请求
      this.$axios({
        url: "http://localhost:9091/user/update",
        method: "post",
        data: this.userForm
      }).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.dialogVisible = false; // 关闭模态框
          // 清除 Cookie
          removeToken();
          // 密码被修改，重定向到登录页面
          this.$router.push('/userLogin');
          this.resetForm();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },

    resetForm() {
      // 重置表单数据为初始状态
      this.userForm = {
        id: 0,
        username: '',
        password: '',
        iphone: '',
        src: '',
      };
    },
    //关闭模态框
    guanbi() {
      this.dialogVisible = false;
      this.resetForm()
      // window.location.reload(true);
      this.selectName()
    },
    // --------------------------------图片上传-------------------------------------------------------
    handleAvatarSuccess(res) {
      this.userForm.src = res.data;
    },
    beforeAvatarUpload(file) {
      // 检查文件类型是否为 JPG, PNG 或 WebP
      const isJPGorPNGorWebP = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2; // 检查文件大小是否小于 2MB

      if (!isJPGorPNGorWebP) {
        this.$message.error('上传头像图片只能是 JPG, PNG 或 WebP 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGorPNGorWebP && isLt2M;
    },

    handleSelect(key, keyPath) {
      if (key === '7') {
        this.showWechatImage = true;
      } else {
        // 如果不是 "7"，则可能需要隐藏图片
        this.showWechatImage = false;
      }
      if (key === '2') {
        this.showWechatImage2 = true;
      } else {
        // 如果不是 "7"，则可能需要隐藏图片
        this.showWechatImage2 = false;
      }
      if (key === '1') {
        this.showCarousel = true;
        this.showPersonalCenter = false;
      } else if (key === '3' && !this.username) {
        this.$router.push('/userLogin');
      } else {
        console.log('选中菜单项:', key, keyPath);
      }
    },
    // handleCommand(command) {
    //   if (command === 'logout') {
    //     this.username = '';
    //     this.src = '';
    //     // document.cookie = "username=" + encodeURIComponent(this.username) + "; path=/; max-age=" + (0);
    //     // this.showPersonalCenter = false;
    //     // this.showCarousel = true;
    //     // this.cartCount = 0;
    //     removeToken();
    //     this.$router.replace('/');
    //     // window.location.reload(true);
    //   } else if (command === 'personal') {
    //     this.showPersonalCenter = true;
    //     this.showCarousel = false;
    //     this.selectName();
    //   }
    // },
    handleCommand(command) {
      if (command === 'logout') {
        this.username = '';
        this.src = '';
        removeToken();
        this.$router.replace('/').catch(err => {
          // 处理 NavigationDuplicated 错误
          if (err.name !== 'NavigationDuplicated') {
            console.error(err);
          }
        });
        this.showPersonalCenter = false;
        this.showCarousel = true;
      } else if (command === 'personal') {
        this.showPersonalCenter = true;
        this.showCarousel = false;
        this.selectName();
      }
    },

    getCookie(name) {
      let nameEQ = name + "=";
      let ca = document.cookie.split(';');
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
      }
      return '';
    },

    // getToken() {
    //   // 从本地存储或Cookie中获取认证Token
    //   return localStorage.getItem('userToken');
    // },

    getToken() {
      request({
        method: 'post',
        url: 'http://localhost:9091/user/getTook',
      }).then(res => {
        if (res.data.code === 200) {
          console.log(res)
          if (res.data.data != null) {
            this.username = res.data.data.username
            this.users = res.data.data;
            this.users.username = this.username;
            this.src = res.data.data.src
            this.selectName();
          }
        }
      })
    },

    //根据用户名查询
    selectName() {
      request({
        method: 'post',
        url: 'http://localhost:9091/user/selectOne',
      }).then(res => {
        if (res.data && res.data.data && res.data.data.src) {
          this.users = [res.data.data];// 将对象包装在数组中
          this.userForm = res.data.data;
          this.src = res.data.data.src;
          this.uid = res.data.data.id
          this.originalPassword = res.data.data.password; // 设置原始密码
          this.selectCreatCount();
        } else {
          console.error('头像数据获取失败');
        }
      })
    },

    // 查询当前登入的用户有几条数据
    selectCreatCount() {
      // 如果名字为空this.cartCount = 0;
      if (this.username == '' && this.username == null) {
        this.cartCount = 0;
      } else {
        this.$axios({
          method: 'post',
          url: 'http://localhost:9091/creat/selectCreatCount',
          params: {
            uid: this.uid  // 将uid作为请求参数发送
          },
        }).then(res => {
          if (res.data && res.data.data) {
            this.cartCount = res.data.data;
          } else {
            console.error('查询失败');
          }
        }).catch(error => {
          console.error('请求错误:', error);
        });
      }
    },

    //错误处理图像
    errorHandler() {
      return true
    },
  },
  created() {
    // this.username = this.getCookie('username');
    // this.user.username = this.username;
    // this.selectName();
    this.getToken()
  },
};
</script>

<style scoped>
.wechat-menu-item {
  position: relative; /* 确保菜单项是相对定位 */
}

.wechat-image-box {
  position: absolute;
  bottom: 100%; /* 将图片放在菜单项的正下方 */
  left: 50%; /* 水平居中 */
  transform: translateX(-50%); /* 修正居中对齐 */
  display: flex;
  justify-content: center; /* 居中显示图片 */
  align-items: center; /* 垂直居中 */
  z-index: 100; /* 确保图片在其他内容之上 */
}

.wechat-image-box img {
  width: 100px; /* 根据需要调整图片大小 */
  height: auto;
  border-radius: 4px; /* 根据需要添加圆角 */
  box-shadow: 0 2px 6px rgba(0,0,0,0.2); /* 添加阴影效果 */
}


.wechat-image-container {
  position: absolute;
  right: 10px;
  top: 60px; /* 根据实际需要调整 */
  z-index: 1000; /* 确保在最上层 */
}

.logo[data-v-0cec1358] {
  font-size: 10px;
  font-weight: bold;
  height: 65px;
  width: 40px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  color: #333;
  height: 60px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
  margin-left: 24px;
}

.top-nav-menu {
  display: flex;
  justify-content: center;
  width: 70%;
  align-items: center;
}

.cart-menu-item {
  position: relative;
  display: flex;
  align-items: center;
}

.item {
  margin: 0 10px;
  display: flex;
  align-items: center;
}

.el-icon-shopping-cart-2 {
  font-size: 20px;
}

.el-badge__content.is-fixed {
  position: absolute;
  top: 50%;
  transform: translateY(-50%) translateX(50%);
  min-width: 20px;
  height: 20px;
  border-radius: 10px;
  background-color: #f56c6c;
  color: #fff;
  text-align: center;
  line-height: 20px;
  padding: 0 5px;
  font-size: 12px;
  right: 0;
}

/*111111111111111*/
.footer {
  background-color: #a9c5a1;
  height: 275px;
  color: #fff;
  padding: 0 0;
  font-size: 14px;
  text-align: center;
  position: relative;
  top: -3px;
}

.container {
  width: 90%;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.footer-links, .footer-contact, .footer-legal, .footer-social {
  flex: 1;
  margin: 10px 0;
}

.footer-links h3, .footer-contact h3, .footer-legal, .footer-social {
  margin-bottom: 10px;
}

.footer-links ul {
  list-style: none;
  padding: 0;
}

.footer-links li {
  line-height: 1.5;
}

.footer-social .social-icon {
  display: inline-block;
  margin-right: 10px;
  font-size: 24px;
  transition: color 0.3s;
}

.footer-social .social-icon:hover {
  color: #ffd700; /* 金色 */
}

@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }

  .footer-links, .footer-contact, .footer-legal, .footer-social {
    flex-basis: auto;
    width: 100%;
    margin-bottom: 20px;
  }
}

/*个人中心样式*/
.personal-center {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.form-footer {
  margin-top: 20px;
  text-align: right;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.wechat-image-container {
  position: absolute;
  right: 10px;
  top: 60px; /* 根据实际需要调整 */
}

.video-container {
  /* 添加样式以确保视频容器可见 */
  position: relative;
  width: 100%;
  padding: 20px;
}

</style>